package gov.pbc.nn.core.job;

import java.io.ByteArrayInputStream;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;



import gov.pbc.nn.core.bdf.entity.User;


import gov.pbc.nn.core.dao.PbcnnCoreJdbcDao;

import javax.annotation.Resource;

import org.apache.axis.AxisFault;
import org.apache.commons.lang.math.RandomUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.Session;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Component;



import gov.pbc.nn.core.job.SynchronousDataService;
import gov.pbc.nn.core.job.SynchronousDataServiceLocator;
import gov.pbc.nn.core.job.SynchronousDataSoapBindingStub;

import com.bstek.bdf2.core.CoreHibernateDao;
import com.bstek.bdf2.core.model.UserDept;
import com.bstek.bdf2.core.orm.hibernate.ISessionCallback;


//@SuppressWarnings("deprecation")
@Component(JobUpdateUser.BEAN_ID)
public class JobUpdateUser extends CoreHibernateDao implements Job    {
	public static final String BEAN_ID = "gov.pbc.nn.core.job.JobUpdateUser";
			

	@Autowired
	@Qualifier("bdf2.passwordEncoder")
	private PasswordEncoder passwordEncoder;
	
	@Resource(name = PbcnnCoreJdbcDao.BEAN_ID)
	private PbcnnCoreJdbcDao jdbcDao;
		
	
	
	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		// TODO Auto-generated method stub
		SAXReader reader = new SAXReader();
		// 通过read方法读取一个文件 转换成Document对象
		Document document = null;
		String msg = "";
		SynchronousDataService locator = new SynchronousDataServiceLocator();
		//SynchronousDataSoapBindingStub stub = (SynchronousDataSoapBindingStub)locator.getSynchronousData();
		java.net.URL url = null;
		try {
			url = new java.net.URL("http://11.72.25.118:8080/loginoa/services/SynchronousData.jws?wsdl");
			try {
				SynchronousDataSoapBindingStub stub = new SynchronousDataSoapBindingStub(url, locator);
				String syscode = "0001";
				msg = stub.getSynPersonDatas(syscode);
			} catch (AxisFault e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (MalformedURLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		String msg1 = msg.replace("encoding='UTF-8'?", "encoding='GBK'?");
		try {
			document = reader.read(new ByteArrayInputStream(msg1.getBytes()));
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 获取根节点元素对象
		Element node = document.getRootElement();
		//String type = node.getName();

		final List<Element> list1 = new ArrayList<Element>();
		list1.addAll(node.elements());
		//int i = list1.size();
		if(list1.size() > 0){
			this.doInHibernateSession(new ISessionCallback<Void>() {

				@Override
				public Void doInSession(Session session) {
					
					//int p = list1.size();
					for (int i = 0; i < (list1.size() - 1); i++) {
						String type = list1.get(i).attributeValue("operType");
						User u = new User();
						
						if(type.equals("add")){
							u.setUsername((list1.get(i).element("uid").getText()));
						}
						else{
							Map<String, Object> list = loadUserByFKsysname(list1.get(i).element("uid").getText());
							u.setUsername((String)list.get("USERNAME_"));
							u.setPassword((String)list.get("PASSWORD_"));
						}
						
						u.setFkSysName((list1.get(i).element("uid").getText()));
						
						u.setCname(list1.get(i).element("username").getText());
						u.setIdentity(list1.get(i).element("pbcIdCard").getText());
						
						String female = list1.get(i).element("pbcgender").getText();
						u.setMale(female.equals("1")?false:true);
						
						// 数据库设置不能为空
						u.setCompanyId("PBCNN");
						int salt = 0;
						if(type.equals("add")){
							salt = RandomUtils.nextInt(1000);
							u.setSalt(String.valueOf(salt));
							String password = "password";
							u.setPassword(passwordEncoder.encodePassword(password, salt));
						}
						else if(type.equals("changepassword")){
							salt = RandomUtils.nextInt(1000);
							u.setSalt(String.valueOf(salt));
							String password = list1.get(i).element("userpassword").getText();
							u.setPassword(passwordEncoder.encodePassword(password, salt));
						}
		
						if(type.equals("add")){
							session.save(u);
						}
						else if(type.equals("delete")){
							session.delete(u);
						}
						else{
							session.update(u);
						}
						// 保存用户关系
						UserDept ud = new UserDept();
						if(type.equals("add")){
							ud.setId(UUID.randomUUID().toString());
						}
						else{
							ud.setId(loadIDByUsername(u.getUsername()));
						}
						ud.setUsername(u.getUsername());
						String deptIdDirt = list1.get(i).element("departmentnumber").getText();

						ud.setDeptId(deptIdDirt);
						// session.save(ud);
						if(type.equals("add")){
							session.save(ud);
						}
						else if(type.equals("delete")){
							session.delete(ud);
						}
						else{
							session.update(ud);
						}
						
						session.flush();
						session.clear();
					}
					
					SynchronousDataService locator = new SynchronousDataServiceLocator();
					//SynchronousDataSoapBindingStub stub = (SynchronousDataSoapBindingStub)locator.getSynchronousData();
					java.net.URL url = null;
					String synendtime = list1.get(list1.size() - 1).getText();
					try {
						String syscode = "0001";
						url = new java.net.URL("http://11.72.25.118:8080/loginoa/services/SynchronousData.jws?wsdl");
						SynchronousDataSoapBindingStub stub = new SynchronousDataSoapBindingStub(url, locator);
						String result = stub.delSynPersonDatas(syscode, synendtime);
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (AxisFault e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return null;
				}
			});
		}


	}

	public Map<String, Object> loadUserByFKsysname(String username) throws UsernameNotFoundException {
		String sql = "SELECT U.USERNAME_, U.PASSWORD_ FROM T_USER U WHERE U.FK_SYS_NAME_='" +
				username +
				"'";
		List<Map<String, Object>> list = jdbcDao.getJdbcTemplate().queryForList(sql);
		if (list.size() == 0) {
			throw new UsernameNotFoundException("User " + username + " is not exist");
		} else {
			Map<String, Object> list1 = list.get(0);
			return list1;
		}
	}
	
	public String loadIDByUsername(String username) throws UsernameNotFoundException {
		String sql = "SELECT ud.ID_ FROM bdf2_user_dept ud WHERE ud.USERNAME_= '" +
				username +
				"'";
		List<String> list = jdbcDao.getJdbcTemplate().queryForList(sql, String.class);
		if (list.size() == 0) {
			throw new UsernameNotFoundException("User " + username + " is not exist");
		} else {
			//String user = (User) users.get(0);
			
			return list.get(0);
		}
	}
}

